<template>
  <div>
    <el-card>
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
        <el-radio-group v-model="currentType" @change="fetchData">
          <el-radio-button label="batch">批次</el-radio-button>
          <el-radio-button label="year">年份</el-radio-button>
          <el-radio-button label="province">省份</el-radio-button>
          <el-radio-button label="subject-type">科类</el-radio-button>
        </el-radio-group>
        <el-button type="primary" @click="openDialog()">
          新增{{ typeConfig[currentType].label }}
        </el-button>
      </div>
      <el-table :data="tableData" border>
        <el-table-column
          v-for="col in typeConfig[currentType].columns"
          :key="col.prop"
          :label="col.label"
          :width="col.width"
        >
          <template slot-scope="scope">
            <!-- 时间字段格式化 -->
            <span v-if="col.prop === 'createdAt' || col.prop === 'created_at' || col.prop === 'updatedAt' || col.prop === 'updated_at'">
              {{ formatDate(scope.row[col.prop] || scope.row[toCamel(col.prop)] || scope.row[toSnake(col.prop)]) }}
            </span>
            <!-- 其他字段兼容驼峰和下划线 -->
            <span v-else>
              {{ scope.row[col.prop] || scope.row[toCamel(col.prop)] || scope.row[toSnake(col.prop)] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="openDialog(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="queryParams.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size.sync="queryParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog :title="form.id ? '编辑' + typeConfig[currentType].label : '新增' + typeConfig[currentType].label" :visible.sync="dialogVisible">
      <el-form :model="form" label-width="100px">
        <el-form-item v-for="item in typeConfig[currentType].formItems" :key="item.prop" :label="item.label">
          <el-input v-model="form[item.prop]" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'BasicInfoManagement',
  data() {
    return {
      currentType: 'batch',
      tableData: [],
      queryParams: {
        page: 1,
        size: 10
      },
      total: 0,
      dialogVisible: false,
      form: {
        id: null,
        batch_name: '',
        year_name: '',
        province: '',
        type_name: ''
      },
      typeConfig: {
        batch: {
          label: '批次',
          columns: [
            { prop: 'id', label: 'ID', width: 60 },
            { prop: 'batch_name', label: '批次名称' },
            { prop: 'created_at', label: '创建时间' },
            { prop: 'updated_at', label: '更新时间' }
          ],
          formItems: [
            { prop: 'batch_name', label: '批次名称' }
          ],
          api: {
            list: '/api/admin/batch/list',
            add: '/api/admin/batch',
            update: '/api/admin/batch',
            delete: '/api/admin/batch/'
          }
        },
        year: {
          label: '年份',
          columns: [
            { prop: 'id', label: 'ID', width: 60 },
            { prop: 'year_name', label: '年份' },
            { prop: 'created_at', label: '创建时间' },
            { prop: 'updated_at', label: '更新时间' }
          ],
          formItems: [
            { prop: 'year_name', label: '年份' }
          ],
          api: {
            list: '/api/admin/year/list',
            add: '/api/admin/year',
            update: '/api/admin/year',
            delete: '/api/admin/year/'
          }
        },
        province: {
          label: '省份',
          columns: [
            { prop: 'id', label: 'ID', width: 60 },
            { prop: 'province', label: '省份名称' },
            { prop: 'created_at', label: '创建时间' },
            { prop: 'updated_at', label: '更新时间' }
          ],
          formItems: [
            { prop: 'province', label: '省份名称' }
          ],
          api: {
            list: '/api/admin/province/list',
            add: '/api/admin/province',
            update: '/api/admin/province',
            delete: '/api/admin/province/'
          }
        },
        'subject-type': {
          label: '科类',
          columns: [
            { prop: 'id', label: 'ID', width: 60 },
            { prop: 'type_name', label: '科类名称' },
            { prop: 'created_at', label: '创建时间' },
            { prop: 'updated_at', label: '更新时间' }
          ],
          formItems: [
            { prop: 'type_name', label: '科类名称' }
          ],
          api: {
            list: '/api/admin/subject-type/list',
            add: '/api/admin/subject-type',
            update: '/api/admin/subject-type',
            delete: '/api/admin/subject-type/'
          }
        }
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      const api = this.typeConfig[this.currentType].api.list
      axios.get(api, {
        params: { page: this.queryParams.page, size: this.queryParams.size }
      }).then(res => {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      })
    },
    handleCurrentChange(page) {
      this.queryParams.page = page;
      this.fetchData();
    },
    handleSizeChange(size) {
      this.queryParams.size = size;
      this.queryParams.page = 1;
      this.fetchData();
    },
    openDialog(row) {
      if (row) {
        // 初始化表单，确保所有字段都有值
        this.form = {
          id: row.id,
          batch_name: '',
          year_name: '',
          province: '',
          type_name: ''
        }
        
        // 根据当前类型，设置正确的字段值（处理驼峰/下划线不一致）
        if (this.currentType === 'batch') {
          this.form.batch_name = row.batch_name || row.batchName || ''
        } else if (this.currentType === 'year') {
          this.form.year_name = row.year_name || row.yearName || ''
        } else if (this.currentType === 'province') {
          this.form.province = row.province || ''
        } else if (this.currentType === 'subject-type') {
          this.form.type_name = row.type_name || row.typeName || ''
        }
        
        // 打印表单数据，方便调试
        console.log('编辑表单数据:', this.form)
      } else {
        this.form = {
          id: null,
          batch_name: '',
          year_name: '',
          province: '',
          type_name: ''
        }
      }
      this.dialogVisible = true
    },
    handleSubmit() {
      const apiConfig = this.typeConfig[this.currentType].api
      
      // 类型必填校验
      if (this.currentType === 'batch' && (!this.form.batch_name || this.form.batch_name.trim() === '')) {
        this.$message.error('批次名称不能为空')
        return
      }
      if (this.currentType === 'year' && (!this.form.year_name || this.form.year_name.trim() === '')) {
        this.$message.error('年份不能为空')
        return
      }
      if (this.currentType === 'province' && (!this.form.province || this.form.province.trim() === '')) {
        this.$message.error('省份不能为空')
        return
      }
      if (this.currentType === 'subject-type' && (!this.form.type_name || this.form.type_name.trim() === '')) {
        this.$message.error('科类名称不能为空')
        return
      }
      
      // 根据当前类型构造提交数据，确保字段名与后端期望的一致
      let submitData = { id: this.form.id }
      
      if (this.currentType === 'batch') {
        // 尝试两种字段名格式（批次）
        submitData.batch_name = this.form.batch_name
        submitData.batchName = this.form.batch_name
      } else if (this.currentType === 'year') {
        // 尝试两种字段名格式（年份）
        submitData.year_name = this.form.year_name
        submitData.yearName = this.form.year_name
      } else if (this.currentType === 'province') {
        // 省份
        submitData.province = this.form.province
      } else if (this.currentType === 'subject-type') {
        // 尝试两种字段名格式（科类）
        submitData.type_name = this.form.type_name
        submitData.typeName = this.form.type_name
      }
      
      // 打印提交的数据，便于调试
      console.log('提交的数据:', submitData)
      
      if (this.form.id) {
        axios.put(apiConfig.update, submitData).then(() => {
          this.$message.success('修改成功')
          this.dialogVisible = false
          this.fetchData()
        }).catch(err => {
          console.error('修改失败:', err)
          this.$message.error('修改失败: ' + (err.response?.data?.message || err.message || '未知错误'))
        })
      } else {
        axios.post(apiConfig.add, submitData).then(() => {
          this.$message.success('新增成功')
          this.dialogVisible = false
          this.fetchData()
        }).catch(err => {
          console.error('新增失败:', err)
          this.$message.error('新增失败: ' + (err.response?.data?.message || err.message || '未知错误'))
        })
      }
    },
    handleDelete(id) {
      const api = this.typeConfig[this.currentType].api.delete
      this.$confirm('确定删除吗？')
        .then(() => {
          axios.delete(`${api}${id}`).then(() => {
            this.$message.success('删除成功')
            this.fetchData()
          }).catch(err => {
            // 取出所有可能的错误信息
            let msg = '';
            if (err.response) {
              if (typeof err.response.data === 'string') {
                msg = err.response.data;
              } else if (err.response.data && err.response.data.message) {
                msg = err.response.data.message;
              } else if (err.response.data) {
                msg = JSON.stringify(err.response.data);
              }
            }
            if (!msg && err.message) msg = err.message;

            // 统一转小写判断
            const msgLower = msg.toLowerCase();

            if (
              msgLower.includes('foreign key constraint fails') ||
              msgLower.includes('cannot delete or update a parent row')
            ) {
              this.$message.error('该数据已被其他数据引用，无法删除！')
            } else {
              this.$message.error('删除失败: ' + (msg || '未知错误'))
            }
          })
        })
        .catch(() => {
          // 用户取消，无需处理
        })
    },
    formatDate(dateStr) {
      if (!dateStr) return ''
      const d = new Date(dateStr)
      const y = d.getFullYear()
      const m = (d.getMonth() + 1).toString().padStart(2, '0')
      const day = d.getDate().toString().padStart(2, '0')
      return `${y}-${m}-${day}`
    },
    toCamel(str) {
      return str.replace(/_([a-z])/g, (g) => g[1].toUpperCase())
    },
    toSnake(str) {
      return str.replace(/[A-Z]/g, (m) => '_' + m.toLowerCase())
    }
  }
}
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 